package com.wangsh.userscenter.head.controller;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.userscenter.common.controller.BaseController;
import com.wangsh.userscenter.common.util.ConstatFinalUtil;
import com.wangsh.userscenter.common.util.PageInfoUtil;
import com.wangsh.userscenter.users.pojo.AUsers;
import com.wangsh.userscenter.users.pojo.AUsersEnum;
import com.wangsh.userscenter.users.service.IUsersOperService;
import com.wangsh.userscenter.users.service.IUsersService;

/**
 * 用户登陆后的主页面
 * @author wangsh_sxt
 *
 */
@Controller
@RequestMapping("/head/users/")
public class UsersHeadController extends BaseController
{
	@Resource
	private IUsersService usersService;
	@Resource
	private IUsersOperService usersOperService;
	
	/**
	 * 用户首页
	 * @return
	 */
	@RequestMapping("/main.html")
	public String main()
	{
		return "/head/users/main";
	}
	
	/**
	 * 用户列表
	 * @return
	 */
	@RequestMapping("/usersList.html")
	public String usersList(HttpServletRequest request)
	{
		/* 接收参数 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");

		if (keyword == null)
		{
			keyword = "";
		}
		keyword = keyword.trim();
		if (status == null)
		{
			status = "";
		}
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}

		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
		}

		/* 查询数据 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyword", "%" + keyword + "%");
		condMap.put("status", status);
		condMap.put("st", stDate);
		condMap.put("ed", edDate);
		Map<String, Object> resultMap = this.usersService.findCondListUsersService(pageInfoUtil, condMap);
		List<AUsers> usersList = (List<AUsers>) resultMap.get("list") ; 
		
		/* 存储结果 */
		request.setAttribute("usersList", usersList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		return "/head/users/usersList";
	}
	
	/**
	 * 用户更新
	 * @return
	 */
	@RequestMapping("/usersUpdate.html")
	public String usersUpdate(HttpServletRequest request)
	{
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "1");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", users.getId()) ; 
		condMap.put("extend", "true");
		users = this.usersService.findOneUsersService(condMap);
		/* 设置头像 */
		request.setAttribute("users", users);
		
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			return "/head/users/usersUpdate";
		}else if("updatePass".equalsIgnoreCase(operType))
		{
			return "/head/users/usersPass";
		}else if("updateEmail".equalsIgnoreCase(operType))
		{
			return "/head/users/usersEmail";
		}else if("updatePhoto".equalsIgnoreCase(operType))
		{
			return "/head/users/usersPhoto";
		}
		return "/head/users/usersInfo";
	}
	
	/**
	 * 用户更新提交
	 * @return
	 */
	@RequestMapping("/usersUpdateSubmit.html")
	public String usersUpdateSubmit(AUsers users,HttpServletRequest request)
	{
		/* 从session中获取信息 */
		AUsers usersRes = (AUsers) this.findObjfromSession(request, "1");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", usersRes.getId()) ; 
		condMap.put("extend", "true");
		usersRes = this.usersService.findOneUsersService(condMap);
		
		/* 更新标志 */
		boolean updateFlag = false ; 
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 修改个人信息 */
			String nickName = request.getParameter("nickName");
			String qq = request.getParameter("qq");
			String address = request.getParameter("address");
			String regionId = request.getParameter("regionId");
			
			/* 生日 */
			String birthdayStr = request.getParameter("birthdayStr");
			usersRes.setBirthday(this.dateFormatUtil.strDate(birthdayStr));
			
			usersRes.setTrueName(users.getTrueName());
			usersRes.setNickName(nickName);
			usersRes.setQq(qq);
			usersRes.setAddress(address);
			usersRes.setSex(users.getSex());
			usersRes.setPhone(users.getPhone());
			
			usersRes.setRegionId(Integer.valueOf(regionId));
			updateFlag = true ; 
		}else if("updatePass".equalsIgnoreCase(operType))
		{
			/* 处理修改密码和重置密码 */
			String souPass = request.getParameter("souPass");
			if(!this.encryptUtil.checkStr(souPass, usersRes.getPassword()))
			{
				this.info = "原密码不正确" ; 
				updateFlag = false ;
			}else
			{
				/* 新密码 */
				String password = request.getParameter("password");
				usersRes.setPassword(this.encryptUtil.encodeStr(password));
				updateFlag = true ;
			}
		}else if("updateEmail".equalsIgnoreCase(operType))
		{
			/* 处理修改密码和重置密码 */
			String souPass = request.getParameter("souPass");
			if(!this.encryptUtil.checkStr(souPass, usersRes.getPassword()))
			{
				this.info = "原密码不正确" ; 
				updateFlag = false ;
			}else
			{
				/* 新密码 */
				String email = request.getParameter("email");
				usersRes.setEmail(email);
				usersRes.setEmailStatus(AUsersEnum.EMAILSTATUS_NO_PASSED.getStatus());
				updateFlag = true ;
			}
		}
		
		if(updateFlag)
		{
			usersRes.setUpdateTime(new Date());
			JSONObject dbJSON = this.usersService.updateOneUsersService(usersRes);
			ConstatFinalUtil.SYS_LOGGER.info("用户修改信息:id:{},邮箱:{},db执行结果:{}",usersRes.getId() , usersRes.getEmail(),dbJSON);
			if("0".equalsIgnoreCase(dbJSON.getString("code")))
			{
				info = "更新成功" ; 
				if("updateEmail".equalsIgnoreCase(operType))
				{
					//邮件验证邮件已经发出
					return "redirect:/emailVerfySend.html?email=" + usersRes.getEmail() ; 
				}
			}else 
			{
				info = dbJSON.getString("info") ; 
			}
		}
		request.setAttribute("info", info);
		return this.usersUpdate(request);
	}
	
	/**
	 * 用户更新提交
	 * @return
	 */
	@RequestMapping("/usersUpdatePhotoSubmit.html")
	public String usersUpdatePhotoSubmit(HttpServletRequest request)
	{
		/* 从session中获取信息 */
		AUsers users = (AUsers) this.findObjfromSession(request, "1");
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", users.getId()) ; 
		condMap.put("extend", "true");
		users = this.usersService.findOneUsersService(condMap);
		
		try
		{
			/* 更新标志 */
			if(request instanceof MultipartRequest)
			{
				MultipartRequest multipartRequest = (MultipartRequest) request ;
				MultipartFile multipartFile = multipartRequest.getFile("file");
				users.setUpdateTime(new Date());
				JSONObject dbJSON = this.usersService.updateOneUsersService(users , multipartFile);
				ConstatFinalUtil.SYS_LOGGER.info("用户修改信息:id:{},邮箱:{},db执行结果:{}",users.getId() , users.getEmail(),dbJSON);
				if("0".equalsIgnoreCase(dbJSON.getString("code")))
				{
					info = "更新成功" ; 
				}else 
				{
					info = dbJSON.getString("info") ; 
				}
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新图片失败了;" , e );
		}
		request.setAttribute("info", info);
		return this.usersUpdate(request);
	}
	
	/**
	 * 退出操作
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/logout.html")
	public String logout(HttpServletRequest request,HttpServletResponse response,String returnUrl) throws Exception
	{
		info = "成功退出" ; 
		HttpSession session = request.getSession();
		AUsers users = (AUsers) this.findObjfromSession(request, "1");
		
		session.removeAttribute("users");
		session.removeAttribute("lastLoginTime");
		
		/* 删除token */
		this.usersOperService.removeUsersTokenService(users);
		
		/* 查找是否有returnUrl */
		if(returnUrl == null)
		{
			returnUrl = "" ; 
		}
		if(!"".equalsIgnoreCase(returnUrl))
		{
			return "redirect:/login.html?returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8");
		}
		return "redirect:/login.html";
	}
}
